// pages/complaint-evaluate/complaint-evaluate.js
import api from "../../../utils/request"
Page({
  data: {
    id: "",
    submitting: false,
    canSubmit: false,

    // 投诉建议详情
    detail: {
      id: "1",
      caseNumber: "TS202312010001",
      type: 0,
      description: "小区内噪音污染严重，影响正常休息，希望物业能够加强管理。",
      replyContent:
        "感谢您的反馈，我们已经安排工作人员加强小区内的巡查，并制定了相关的噪音管理规定。如有问题请及时联系我们。",
      replyTime: "2023-12-02",
      responderName: "张管家",
    },

    // 评价数据
    evaluation: {
      rating: 0, // 1-5星评分
      effectRating: "", // 处理效果：solved/improving/unsolved
      comment: "", // 评价内容
      selectedTags: [], // 选中的快速评价标签
    },

    // 评分文本
    ratingTexts: ["很不满意", "不满意", "一般", "满意", "很满意"],

    // 快速评价标签
    quickTags: [
      { id: 1, text: "回复及时", selected: false },
      { id: 2, text: "态度友好", selected: false },
      { id: 3, text: "解决有效", selected: false },
      { id: 4, text: "专业负责", selected: false },
      { id: 5, text: "沟通顺畅", selected: false },
      { id: 6, text: "处理迅速", selected: false },
      { id: 7, text: "回复详细", selected: false },
      { id: 8, text: "服务周到", selected: false },
    ],
  },

  onLoad(options) {
    if (options.id) {
      this.setData({
        id: options.id,
      })
      this.fetchDetail(options.id)
    }
    this.checkCanSubmit()
  },

  // 获取详情数据
  fetchDetail(id) {
    wx.showLoading({
      title: "加载中...",
    });
  
    // 模拟API请求
    setTimeout(async () => {
      const result = await api.get(`/property/complaint/${id}`);
      const complaintData = result.data;
      this.setData({
        detail: complaintData,
      });
      wx.hideLoading();
    }, 500);
  },

  // 评分变化
  onRatingChange(e) {
    this.setData({
      "evaluation.rating": e.detail,
    })
    this.checkCanSubmit()
  },

  // 处理效果变化
  onEffectChange(e) {
    this.setData({
      "evaluation.effectRating": e.detail,
    })
    this.checkCanSubmit()
  },

  // 评价内容变化
  onCommentChange(e) {
    this.setData({
      "evaluation.comment": e.detail,
    })
  },

  // 快速评价标签点击
  onTagClick(e) {
    const { id } = e.currentTarget.dataset
    const { quickTags } = this.data

    const updatedTags = quickTags.map((tag) => {
      if (tag.id === id) {
        return { ...tag, selected: !tag.selected }
      }
      return tag
    })

    // 更新选中的标签列表
    const selectedTags = updatedTags.filter((tag) => tag.selected).map((tag) => tag.text)

    this.setData({
      quickTags: updatedTags,
      "evaluation.selectedTags": selectedTags,
    })
  },

  // 检查是否可以提交
  checkCanSubmit() {
    const { evaluation } = this.data
    const isValid = evaluation.rating > 0 && evaluation.effectRating

    this.setData({
      canSubmit: isValid,
    })
  },

  // 提交评价
  onSubmit() {
    if (!this.data.canSubmit) {
      wx.showToast({
        title: "请完成必填评价",
        icon: "none",
      })
      return
    }
  
    this.setData({ submitting: true })
  
    // 构建提交数据
    const submitData = {
      id: this.data.id,
      status: 2,
      evaluationContent: this.buildEvaluationContent(),
    }
  
    console.log(submitData)
  
    // 发起 API 请求
    api.put("/property/complaint", submitData).then(result => {
      // 处理成功返回的结果
      this.setData({ submitting: false })
      wx.showToast({
        title: "评价成功",
        icon: "success",
      })
  
      setTimeout(() => {
        // 返回详情页并刷新
        const pages = getCurrentPages()
        const prevPage = pages[pages.length - 2]
        if (prevPage && prevPage.fetchDetail) {
          prevPage.fetchDetail(this.data.id)
        }
        wx.navigateBack()
      }, 1500)
    }).catch(error => {
      // 处理失败的情况
      this.setData({ submitting: false })
      wx.showToast({
        title: "评价失败，请稍后再试",
        icon: "none",
      })
      console.error("提交失败：", error)
    })
  },


  // 构建评价内容
  buildEvaluationContent() {
    const { evaluation, ratingTexts } = this.data
    let content = ""

    // 添加评分
    content += `满意度：${ratingTexts[evaluation.rating - 1]}`

    // 添加处理效果
    const effectTexts = {
      solved: "已解决",
      improving: "正在改善",
      unsolved: "未解决",
    }
    content += `，处理效果：${effectTexts[evaluation.effectRating]}`

    // 添加快速评价标签
    if (evaluation.selectedTags.length > 0) {
      content += `，评价标签：${evaluation.selectedTags.join("、")}`
    }

    // 添加评价内容
    if (evaluation.comment.trim()) {
      content += `，详细评价：${evaluation.comment.trim()}`
    }

    return content
  },
})
